package myJs

import myJs.Implicits._
import myJs.Utils.layer
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 6/5/2021
 */
@JSExportTopLevel("Search")
object Search {

  val tableId = "table"
  val formId = "form"
  val mRnaTabId="mRna"
  val circRnaTabId="circ"
  val pathwayTabId="pathway"
  val cellTabId="cell"

  @JSExport("init")
  def init = {
    refreshGeneSymbol()
    refreshCircGeneSymbol
    refreshPathwayId
    refreshCellId
    registerEvent
    bootStrapValidator
  }

  def refreshGeneSymbol(formJq:JQuery=$(s"#${mRnaTabId} #${formId}"))={
    val url = g.jsRoutes.controllers.MrnaController.getGeneNames().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS
      formJq.findInputByName("id").typeahead("destroy").typeahead(TypeaheadOptions.source(data)
        .highlighter(Tool.highlighterF).updater(Tool.updater).matcher(Tool.matcher))
    }
  }

  def refreshCircGeneSymbol={
    val url = g.jsRoutes.controllers.CircRnaController.getAllCircIdAndGeneName().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS
      $(s"#${circRnaTabId} #${formId}").findInputByName("id").typeahead("destroy").typeahead(TypeaheadOptions.source(data)
        .highlighter(Tool.highlighterF).updater(Tool.updater).matcher(Tool.matcher))
    }
  }

  def refreshPathwayId={
    val url = g.jsRoutes.controllers.PathwayController.getAllIdAndName().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS
      $(s"#${pathwayTabId} #${formId}").findInputByName("id").typeahead("destroy").typeahead(TypeaheadOptions.source(data)
        .highlighter(Tool.highlighterF).updater(Tool.updater).matcher(Tool.matcher))
    }
  }

  def refreshCellId={
    val url = g.jsRoutes.controllers.CellController.getAllName().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS
      $(s"#${cellTabId} #${formId}").findInputByName("id").typeahead("destroy").typeahead(TypeaheadOptions.source(data)
        .highlighter(Tool.highlighterF).updater(Tool.updater).matcher(Tool.matcher))
    }
  }

  @JSExport("showExample")
  def showExample(y: Element, name: String) = {
    val example = $(y).find("em").text().trim
    val formJq = $(y).parents("form")
    formJq.find(s"textarea[name='${name}']").`val`(example)
    formJq.find(s":input[name='${name}']").`val`(example)
    formJq.bv.revalidateField(name)
  }

  def registerEvent = {

  }

  def bootStrapValidator={
    mRnaBv
    circKeywordBv
    circAdvancedBv
    pathwayBv
    cellBv
  }

  def mRnaBv = {
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> {
        js.Dictionary(
          "id" -> {
            val info = "id"
            js.Dictionary(
              "validators" -> js.Dictionary(
                "notEmpty" -> js.Dictionary(
                  "message" -> s"${info} is required！"
                ),
              )
            )
          },
        )
      }
    )
    g.$(s"#mRna #${formId}").bootstrapValidator(dict)
  }

  def circKeywordBv = {
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> {
        js.Dictionary(
          "id" -> {
            val info = "Gene symbol or circRNA ID"
            js.Dictionary(
              "validators" -> js.Dictionary(
                "notEmpty" -> js.Dictionary(
                  "message" -> s"${info} is required！"
                ),
              )
            )
          },
        )
      }
    )
    g.$(s"#circ #keyword #${formId}").bootstrapValidator(dict)
  }

  def circAdvancedBv = {
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> {
        js.Dictionary(
          "start" -> {
            val info = "Start Location"
            js.Dictionary(
              "validators" -> js.Dictionary(
                "notEmpty" -> js.Dictionary(
                  "message" -> s"${info} is required！"
                ),
                "integer" -> js.Dictionary(
                  "message" -> s"${info} must be an integer！",
                ),
                "between" -> js.Dictionary(
                  "min" -> 1,
                  "max" -> maxNumber,
                  "message" -> s"${info} must be greater than 0！",
                ),
              )
            )
          },
          "end" -> {
            val info = "End Location"
            js.Dictionary(
              "validators" -> js.Dictionary(
                "notEmpty" -> js.Dictionary(
                  "message" -> s"${info} is required！"
                ),
                "integer" -> js.Dictionary(
                  "message" -> s"${info} must be an integer！",
                ),
                "between" -> js.Dictionary(
                  "min" -> "start",
                  "max" -> maxNumber,
                  "message" -> s"${info} must be greater than start！",
                ),
              )
            )
          },
        )
      }
    )
    g.$(s"#circ #advanced #${formId}").bootstrapValidator(dict)
  }

  def pathwayBv = {
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> {
        js.Dictionary(
          "id" -> {
            val info = "Pathway ID or name"
            js.Dictionary(
              "validators" -> js.Dictionary(
                "notEmpty" -> js.Dictionary(
                  "message" -> s"${info} is required！"
                ),
              )
            )
          },
        )
      }
    )
    g.$(s"#pathway #${formId}").bootstrapValidator(dict)
  }

  def cellBv = {
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> {
        js.Dictionary(
          "id" -> {
            val info = "Tissue/Cell name"
            js.Dictionary(
              "validators" -> js.Dictionary(
                "notEmpty" -> js.Dictionary(
                  "message" -> s"${info} is required！"
                ),
              )
            )
          },
        )
      }
    )
    g.$(s"#cell #${formId}").bootstrapValidator(dict)
  }


}
